package org.example.controller;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
* @description: TODO
* @author 杨镇宇
* @date 2024/8/30 16:20
* @version 1.0
*/
@OpenAPIDefinition(
        info = @io.swagger.v3.oas.annotations.info.Info(
                title = "示例 API",
                version = "1.0",
                description = "这是一个示例 API 文档"
        ),
        tags = {
                @Tag(name = "Example", description = "索引 API")
        }
)
@RestController
@Slf4j
public class IndexController {

    private final RestHighLevelClient client;

    public IndexController(RestHighLevelClient client) {
        this.client = client;
    }

    /**
     * _cat/* 相关API
     *
     * GET /_cat/indices/yzy-*-20240830?v&h=index,pri.store.size&s=ss:desc&bytes=gb
     * GET /_cat/indices/yzy-*-20240830：请求 _cat/indices API，获取匹配模式为 yzy-*-20240830 的索引信息。
     * v：表示显示表头（列名）。
     * h=index,pri.store.size：指定要显示的列，index 是索引名称，pri.store.size 是主分片的存储大小。
     * s=ss:desc：按存储大小（ss）降序排序。
     * bytes=gb：将存储大小以 GB 为单位显示。
     */

    @GetMapping("/api/index_cat")
    public String getIndexCat()   {
        try {
            // 构建 Cat Indices 请求
            Request request = new Request("GET", "/_cat/indices/yzy-*-20240830?v&h=index,pri.store.size&s=ss:desc&bytes=gb");
            // 执行请求
            Response response = client.getLowLevelClient().performRequest(request);
            // 处理响应
            String responseBody = EntityUtils.toString(response.getEntity());
            log.info(responseBody);
            return responseBody;
        } catch (ResponseException e) {
            log.error("Error executing request: " + e.getMessage());
        } catch (IOException i){
            log.error("错误 ",i);

        }
        return null;
    }
    /**
     * 查看所有索引
     */
    @GetMapping("/api/index_all")
    public String getAllIndex()   {
        try {

            // 创建索引请求
            Request request = new Request("GET", "/_cat/indices?v");
            // 执行请求
            Response response = client.getLowLevelClient().performRequest(request);
            String msg = EntityUtils.toString(response.getEntity());
            log.info(msg);
            return msg;
        } catch (ResponseException e) {
            log.error("Error executing request: " + e.getMessage());
        } catch (IOException i){
            log.error("错误 ",i);

        }
        return null;
    }

    /**
     * 创建索引
     *
     * PUT /yzy_test
     * {
     *   "settings": {
     *     "number_of_shards": 1,
     *     "number_of_replicas": 1
     *   },
     *   "mappings": {
     *     "properties": {
     *       "field1": { "type": "text" },
     *       "field2": { "type": "keyword" }
     *     }
     *   }
     * }
     */
    @GetMapping("/api/index_create")
    public String getIndexCreate()   {
        try {

            // 创建索引请求
        Request request = new Request("PUT", "/yzy_test");
        String jsonString = "{ \"settings\": { \"number_of_shards\": 1, \"number_of_replicas\": 1 }, " +
                "\"mappings\": { \"properties\": { \"field1\": { \"type\": \"text\" }, \"field2\": { \"type\": \"keyword\" } } } }";
        request.setJsonEntity(jsonString);

        // 执行请求
        Response response = client.getLowLevelClient().performRequest(request);
        String msg = EntityUtils.toString(response.getEntity());
        log.info(msg);
        return msg;
        } catch (ResponseException e) {
            log.error("Error executing request: " + e.getMessage());
        } catch (IOException i){
            log.error("错误 ",i);

        }
        return null;
    }
    /**
     * 检索索引
     * GET /yzy_test
     */
    @GetMapping("/api/index_get")
    public String getGetIndex()   {
        try {

            // 创建索引请求
            Request request = new Request("GET", "/yzy_test");
                       // 执行请求
            Response response = client.getLowLevelClient().performRequest(request);
            String msg = EntityUtils.toString(response.getEntity());
            log.info(msg);
            return msg;
        } catch (ResponseException e) {
            log.error("Error executing request: " + e.getMessage());
        } catch (IOException i){
            log.error("错误 ",i);

        }
        return null;
    }
    /**
     * 删除索引
     * DELETE /yzy_test
     */
    @GetMapping("/api/index_delete")
    public String getDelIndex()   {
        try {

            // 创建索引请求
            Request request = new Request("DELETE", "/yzy_test");
            // 执行请求
            Response response = client.getLowLevelClient().performRequest(request);
            String msg = EntityUtils.toString(response.getEntity());
            log.info(msg);
            return msg;
        } catch (ResponseException e) {
            log.error("Error executing request: " + e.getMessage());
        } catch (IOException i){
            log.error("错误 ",i);
        }
        return null;
    }


    /**
     * 新增文档
     */
    @GetMapping("/api/doc_create")
    public void createDocument() {
        try {
            // 创建 IndexRequest 对象，指定索引名称和文档ID
            IndexRequest request = new IndexRequest("yzy-app-a-20240830").id("1");

            // 设置文档内容
            String jsonString = "{" +
                    "\"user\":\"kimchy\"," +
                    "\"postDate\":\"2023-08-30\"," +
                    "\"message\":\"trying out Elasticsearch\"" +
                    "}";
            request.source(jsonString, XContentType.JSON);

            // 执行请求
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            log.info( "Document add: " + response.getResult());

        } catch (IOException e) {
            log.error("Error creating document", e);
        }
    }
    /**
     * 更新文档
     */
    @GetMapping("/api/doc_update")
    public void updateDocument() {
        try {
            // 创建 UpdateRequest 对象，指定索引名称和文档ID
            UpdateRequest request = new UpdateRequest("yzy-app-a-20240830", "1");

            // 设置更新内容
            String jsonString = "{" +
                    "\"message\":\"updating document content\"" +
                    "}";
            request.doc(jsonString, XContentType.JSON);

            // 执行请求
            UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
            log.info( "Document update: " + response.getResult());

        } catch (IOException e) {
            log.error("Error updating document", e);
        }
    }

    /**
     * 删除文档
     */
    @GetMapping("/api/doc_delete")
    public void deleteDocument() {
        try {
            // 创建 DeleteRequest 对象，指定索引名称和文档ID
            DeleteRequest request = new DeleteRequest("yzy-app-a-20240830", "1");

            // 执行请求
            DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);

            log.info( "Document deleted: " + response.getResult());
        } catch (IOException e) {
            log.error("Error deleting document", e);
        }
    }


    /**
     * 根据索引中的文档 ID 查询文档
     */
    @GetMapping("/api/doc/{index}/{id}")
    public String getDocumentById(@PathVariable String index, @PathVariable String id) {
        try {
            // 创建 GetRequest 对象，指定索引名称和文档ID
            GetRequest getRequest = new GetRequest(index, id);

            // 执行查询
            GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);

            // 判断文档是否存在
            if (getResponse.isExists()) {
                // 返回文档内容
                return getResponse.getSourceAsString();
            } else {
                return "Document not found";
            }
        } catch (Exception e) {
            // 错误处理
            e.printStackTrace();
            return "Error retrieving document: " + e.getMessage();
        }
    }

}
